import React, { useState, useEffect } from 'react';
import { Card, Table, Button, Space, MessagePlugin, Popconfirm } from 'tdesign-react';
import { getFloorListAPI, deleteFloorAPI } from '@/api/floor.api';
import FloorForm from './components/FloorForm';
import { IFloor, FLOOR_TABLE_COLUMNS, IApiResponse } from './consts';
import { PrimaryTableCol } from 'tdesign-react/es/table/type';

const FloorManage: React.FC = () => {
  const [loading, setLoading] = useState(false);
  const [floorList, setFloorList] = useState<IFloor[]>([]);
  const [showAddDialog, setShowAddDialog] = useState(false);

  /**
   * 获取楼层列表数据
   * @async
   * @function fetchFloorList 
   * @description 异步获取楼层列表数据，处理成功/失败状态并更新 loading 状态
   * @throws {Error} 当API请求失败时抛出错误并显示错误提示
   */
  const fetchFloorList = async () => {
    try {
      setLoading(true);
      const res = await getFloorListAPI() as IApiResponse<IFloor[]>;
      if (res.status === 200) {
        setFloorList(res.data.data || []);
      }
    } catch (error) {
      MessagePlugin.error('获取楼层列表失败');
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    fetchFloorList();
  }, []);

  /**
   * 删除楼层
   * @param record 楼层记录
   * @async
   * @function handleDelete
   * @description 异步删除楼层，处理成功/失败状态并更新 loading 状态
   * @throws {Error} 当 API 请求失败时抛出错误并显示错误提示
   */
  const handleDelete = async (record: IFloor) => {
    try {
      const res = await deleteFloorAPI(record.id) as IApiResponse<any>;
      if (res.status === 200) {
        MessagePlugin.success('删除成功');
        fetchFloorList();
      } else {
        MessagePlugin.error(res.data?.message || '删除失败');
      }
    } catch (error: any) {
      MessagePlugin.error(error.response?.data?.message || '删除失败');
    }
  };

  const columns: PrimaryTableCol<IFloor>[] = [
    ...FLOOR_TABLE_COLUMNS,
    {
      title: '操作',
      colKey: 'operation',
      width: 200,
      fixed: 'right' as const,
      align: 'center' as const,
      cell: ({ row }) => (
        <Space>
          <Popconfirm
            theme="danger"
            content="删除楼层会删除该楼层下的所有包间，确定删除吗？"
            onConfirm={() => handleDelete(row)}
          >
            <Button theme="danger" variant="text">
              删除
            </Button>
          </Popconfirm>
        </Space>
      ),
    },
  ];

  return (
    <Card>
      <Space direction="vertical" style={{ width: '100%' }}>
        <Button theme="primary" onClick={() => setShowAddDialog(true)}>
          新建楼层
        </Button>
        <Table
          loading={loading}
          data={floorList}
          columns={columns}
          rowKey="id"
          pagination={{
            total: floorList.length,
          }}
        />
        <FloorForm
          visible={showAddDialog}
          onClose={() => setShowAddDialog(false)}
          onSuccess={fetchFloorList}
        />
      </Space>
    </Card>
  );
};

export default FloorManage;

